/*
 * @Description: 
 * @Author: HYH
 * @LastEditors: HYH
 * @LastEditTime: 2023-03-31 10:16:07
 */
import { useEffect, useRef, useState } from "react";
import { Outlet } from "react-router-dom";
import flower from '@/assets/img/flower.jpg'
import './index.scss'
import { fabric } from 'fabric'
import { Button } from "antd";
export default () => {
  let rect: fabric.Rect
  let circle: fabric.Circle
  let canvas: fabric.Canvas & Partial<{
    isDragging: boolean,
    lastPosX: number,
    lastPosY: number,
  }>

  useEffect(() => {
    canvas = new fabric.Canvas('can')
    canvas.on('mouse:wheel', opt => {
      let delta = opt.e.deltaY // 滚轮，向上滚一下是 -100，向下滚一下是 100
      let zoom = canvas.getZoom() // 获取画布当前缩放值
      zoom *= 0.999 ** delta
      if (zoom > 20) zoom = 20
      if (zoom < 0.01) zoom = 0.01
      canvas.zoomToPoint({ // 关键点
        x: opt.e.offsetX,
        y: opt.e.offsetY
      },
        zoom
      )
      opt.e.preventDefault()
      opt.e.stopPropagation()
    })
    canvas.on('mouse:down', opt => { // 鼠标按下时触发
      let evt = opt.e
      console.log(`evt ==>`, evt);
      if (evt.altKey === true || evt.ctrlKey === true) { // 是否按住alt
        canvas.isDragging = true // isDragging 是自定义的
        canvas.lastPosX = evt.clientX // lastPosX 是自定义的
        canvas.lastPosY = evt.clientY // lastPosY 是自定义的
      }
    })

    canvas.on('mouse:move', opt => { // 鼠标移动时触发
      if (canvas.isDragging) {
        let evt = opt.e
        let vpt = canvas.viewportTransform! // 聚焦视图的转换
        vpt[4] += evt.clientX - canvas.lastPosX!
        vpt[5] += evt.clientY - canvas.lastPosY!
        canvas.requestRenderAll()
        canvas.lastPosX = evt.clientX
        canvas.lastPosY = evt.clientY
      }
    })

    canvas.on('mouse:up', opt => { // 鼠标松开时触发
      canvas.setViewportTransform(canvas.viewportTransform!) // 设置此画布实例的视口转换  
      canvas.isDragging = false
    })



    // 矩形
    rect = new fabric.Rect({
      left: 250,
      top: 250,
      fill: 'red',
      width: 100,
      height: 100,
      cornerColor: 'hotpink',
      borderColor: 'yellowGreen', // 边框颜色（被选中时）
      borderScaleFactor: 4, // 边框粗细（被选中时）
      borderDashArray: [10, 4, 20], // 创建边框虚线
      selectable: true,//能否被选中，默认true
      shadow: 'rgba(0, 0, 0, 0.5) 5px 5px 5px', // 投影
    })
    rect.animate('angle', 360, {
      onChange: canvas.renderAll.bind(canvas),
      duration: 2000,
      easing: fabric.util.ease.easeOutBounce

    })
    canvas.add(rect)

    //  圆形
    circle = new fabric.Circle(
      {
        left: 100,
        top: 100,
        radius: 50,
        fill: 'green',
        strokeWidth: 5,
        stroke: 'red'

      }
    )


    // 使用 IText，可编辑文本
    const text = new fabric.IText(
      '雷猴啊，双击打几个字试下~',
      {
        fontFamily: 'Comic Sans'
      }
    )
    canvas.add(text)

    // 线性渐变
    const gradient = new fabric.Gradient({
      type: 'linear', // linear or radial
      gradientUnits: 'pixels', // pixels or pencentage 像素 或者 百分比
      coords: { x1: 0, y1: 0, x2: circle.width, y2: 0 }, // 至少2个坐标对（x1，y1和x2，y2）将定义渐变在对象上的扩展方式
      colorStops: [ // 定义渐变颜色的数组
        { offset: 0, color: 'red' },
        { offset: 0.2, color: 'orange' },
        { offset: 0.4, color: 'yellow' },
        { offset: 0.6, color: 'green' },
        { offset: 0.8, color: 'blue' },
        { offset: 1, color: 'purple' },
      ]
    })
    circle.set('fill', gradient);
    canvas.add(circle)

    const circle2 = new fabric.Circle(
      {
        left: 200,
        top: 100,
        radius: 50,
        fill: 'skyblue',
        strokeWidth: 5,
        stroke: 'green'

      }
    )
    let gradient2 = new fabric.Gradient({
      type: 'radial',
      coords: {
        r1: 50, // 该属性仅径向渐变可用，外圆半径
        r2: 0, // 该属性仅径向渐变可用，外圆半径  
        x1: 50, // 焦点的x坐标
        y1: 50, // 焦点的y坐标
        x2: 50, // 中心点的x坐标
        y2: 50, // 中心点的y坐标
      },
      colorStops: [
        { offset: 0, color: '#fee140' },
        { offset: 1, color: '#fa709a' }
      ]
    })

    circle2.set('fill', gradient2)
    canvas.add(circle2)


    // 圆形
    let circle3 = new fabric.Circle({
      radius: 50,
      fill: 'green',
      left: 200,
      top: 200,
      // hasControls: false, // 控件将不显示，并且不能用于操作对象
    })
    canvas.add(circle3)


    // 圆角矩形
    let rect2 = new fabric.Rect({
      left: 300,
      top: 100,
      fill: 'yellowgreen',
      width: 100,
      height: 100,
      rx: 20,
      ry: 20
    })
    canvas.add(rect2)



    // 三角形
    const triangle = new fabric.Triangle(
      {
        left: 200,
        top: 0,
        fill: 'yellow',
        width: 50,
        height: 100

      }
    )
    canvas.add(triangle)

    fabric.Image.fromURL(flower, (img) => {
      img.scale(0.5)
      img.top = 400
      img.filters?.push(new fabric.Image.filters.Blur({ blur: 0.2 }))
      img.applyFilters()
      canvas.add(img)
    })
  }, [])

  // return <Outlet />
  return (
    <div className="container">
      <div>
        <Button onClick={() => { console.log(`canvas.toSVG() ==>`, canvas.toSVG()); }}> svg</Button >
        <Button onClick={() => { console.log(`canvas.toDataURL() ==>`, canvas.toDataURL()); }}> png</Button >

        <Button onClick={() => { canvas.clear() }}> 清空</Button >
        <Button onClick={() => { canvas.remove(circle) }}> 删除圆形</Button >
        <Button onClick={() => {
          canvas.FX_DURATION = 500 // 设置动画时长，默认500毫秒
          canvas.fxRemove(rect,)
        }}> 删除方形（带过渡动画）</Button >
      </div>
      <canvas id="can" width={500} height={500} ></canvas>
    </div >
  )
}